#!/bin/bash

# 检查 landscape2 是否已安装
if ! command -v landscape2 &> /dev/null; then
    echo "landscape2 未安装，正在安装..."
    curl --proto '=https' --tlsv1.2 -LsSf https://github.com/cncf/landscape2/releases/download/v0.13.0/landscape2-installer.sh | sh

    # 更新环境变量
    source $HOME/.cargo/env

    # 再次检查是否安装成功
    if ! command -v landscape2 &> /dev/null; then
        echo "错误: landscape2 安装失败"
        exit 1
    else
        echo "landscape2 安装成功"
    fi
fi

# 检查必要的文件是否存在
required_files=(
    "./gitcode/landscape.yml"
    "./gitcode/settings.yml"
)

for file in "${required_files[@]}"; do
    if [ ! -f "$file" ]; then
        echo "错误: 文件 $file 不存在"
        exit 1
    fi
done

# 检查 logos 目录是否存在
if [ ! -d "./gitcode/hosted_logos" ]; then
    echo "错误: logos 目录不存在"
    exit 1
fi

# 运行landscape检测，检查yaml文件格式是否正确
echo "正在验证配置文件格式..."
landscape2 validate settings --settings-file ./gitcode/settings.yml

if [ $? -ne 0 ]; then
    echo "错误: 配置文件验证失败"
    exit 1
else
    echo "配置文件验证成功"
fi

# 创建输出目录（如果不存在）
mkdir -p dist

echo "开始构建 landscape..."
landscape2 build \
    --data-file ./gitcode/landscape.yml \
    --settings-file ./gitcode/settings.yml \
    --logos-path ./gitcode/hosted_logos \
    --output-dir dist

if [ $? -eq 0 ]; then
    echo "构建成功完成！"
else
    echo "构建失败！"
    exit 1
fi

echo "注入样式"
ADD_STYLE='<style>footer {display: none !important;} div[class*="_catTitleTextWrapper_"] div[class*="_catTitle"] {writing-mode: horizontal-tb; -webkit-transform: none; transform: none; width: 16px; left: 12px; height: 160px;} div[class*="_catTitleTextWrapper_"] div[class*="_catTitle"] div {-webkit-line-clamp: none;} .navbar[class*='_navbar_'] .mainPadding .d-flex.align-items-center button:nth-child(2) {display: none;} div[class*="_subcatTitle_"] div > button {display: none;} .modal-body a[title="Website"],a[title="Repository"] {display: none;} @media only screen and (max-width: 576px) {div[class*="_logoWrapper_"] .dropdown-menu .dropdown-item:nth-of-type(3),.dropdown-item:nth-of-type(4),hr {display: none;}}</style>'
sed -i '/<\/head>/i\    '"$ADD_STYLE" ./dist/index.html

echo "注入JS"
cat >> dist/index.html << 'EOF'
<script>
let domUpdated = false;

function updateDom() {
  const headerContainer = document.querySelector(
    "header.navbar[class*='_navbar_'] .mainPadding"
  );
  if (!headerContainer) {
    return false;
  }

  const githubLink = headerContainer.querySelector(
    "div[class*='_icons_'] a.link"
  );
  if (githubLink) {
    const svgContent = githubLink.innerHTML;
    const svgClassMatch = svgContent.match(/<svg[^>]*class="([^"]*)"[^>]*>/i);
    const svgClass = svgClassMatch ? svgClassMatch[1] : '';
    githubLink.setAttribute("href", "https://gitcode.com");
    githubLink.innerHTML = `<svg class="${svgClass}" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" stroke="currentColor" fill="currentColor" width="20" height="20"><path d="M660.48 212.352l19.2-10.837333 2.346667 11.946666c1.28 6.314667 2.389333 11.477333 2.858666 16.554667 4.096 44.330667 26.368 76.885333 57.898667 84.224 46.165333 10.709333 89.685333-6.997333 113.109333-46.08 28.16-46.848 15.914667-104.277333-32-138.837333C690.56 33.152 544.085333 6.656 386.304 52.949333c-340.181333 100.394667-456.533333 518.272-215.125333 774.570667 103.253333 109.653333 234.453333 156.928 383.317333 153.344 190.72-4.48 328.106667-99.541333 415.786667-264.277333 62.165333-116.864-5.418667-244.608-134.826667-271.146667a837.376 837.376 0 0 0-224.725333-14.378667 188.330667 188.330667 0 0 0-71.466667 21.76c-24.746667 12.8-31.872 39.466667-29.098667 65.92 2.56 24.064 21.034667 38.485333 43.008 42.112 44.245333 6.954667 89.045333 10.965333 133.76 14.634667 12.928 1.109333 26.026667 1.237333 39.04 1.365333 18.688 0.170667 37.376 0.341333 55.637334 3.413334 52.053333 8.533333 69.888 50.773333 43.136 96a186.88 186.88 0 0 1-22.826667 30.293333 259.413333 259.413333 0 0 1-131.413333 77.781333c-92.373333 22.613333-184.832 23.893333-276.778667-5.162666-104.746667-33.024-167.168-109.952-169.344-213.504a359.296 359.296 0 0 1 46.933333-182.229334c14.293333-25.898667 22.144-52.522667 19.925334-81.834666a1166.848 1166.848 0 0 1-2.005334-38.485334l-0.981333-22.4c10.624 2.218667 21.077333 5.034667 31.402667 8.405334 40.021333 16.085333 79.445333 23.466667 122.794666 11.648a222.122667 222.122667 0 0 1 75.349334-4.864 188.586667 188.586667 0 0 0 115.669333-28.245334c8.618667-5.034667 17.365333-9.941333 26.965333-15.36z"></path></svg>`;
  }

  const dropdownMenu = headerContainer.querySelector("ul[class*='_menuList_']");
  if(dropdownMenu) {
    const menuHeaders = dropdownMenu.querySelectorAll("li div[class*='_dropdownHeader_']");
    menuHeaders[0].textContent = "软件图谱";
    menuHeaders[1].textContent = "数据文件";

    const subDescItems = dropdownMenu.querySelectorAll("div[class*='_legend_']");
    subDescItems[0].textContent = "下载 pdf 格式";
    subDescItems[1].textContent = "下载 png 格式";
    subDescItems[2].textContent = "下载 csv 格式，包含所有软件信息";
    subDescItems[3].textContent = "下载 csv 格式，包含所有 project 信息";
  }

  domUpdated = true;
  return true;
}

setTimeout(() => {
  if (!domUpdated) {
    function tryUpdate() {
      if (!domUpdated && !updateDom()) {
        requestAnimationFrame(tryUpdate);
      }
    }
    tryUpdate();
  }
}, 100);

updateDom();
</script>
EOF

# 替换 title 标签内容
sed -i 's/<title>GitCode Landscape<\/title>/<title>GitCode-工业开源软件图谱<\/title>/' dist/index.html

echo "正在启动 landscape 服务器..."
landscape2 serve --landscape-dir dist

if [ $? -eq 0 ]; then
    echo "服务器已成功启动！"
else
    echo "服务器启动失败！"
    exit 1
fi